package com.beanconvert.convert;


import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

import com.beanconvert.common.Convention;
import com.beanconvert.xml.bean.BeanField;
import com.beanconvert.xml.bean.BeanInfo;
import com.beanconvert.xml.bean.SourceBean;



public class CombineBeanImp implements CombineBean {

	// private BeanInfo bi = new BeanInfo();

	@Override
	public Object combineBean(String beanName, Object... oArray) {
		// TODO Auto-generated method stub

		// valid the size of the object number
		int srcBeanNum = oArray.length;
		int srcNum = 0;
		BeanInfo bi = null;

		for (BeanInfo tmpBi : Convention.BEAN_CONVERT_MODEL) {
			if (tmpBi.getName().equalsIgnoreCase(beanName)) {
				bi = tmpBi;
				break;
			}

		}

		if (bi == null) {

			System.out.println("---> Can't find BeanName :" + beanName);
			return null;
		}
System.out.println("==> bi name :"+ bi.getName());

		srcNum = bi.getBeanArray().size();
		if (srcNum != srcBeanNum) {
			System.out.println("==> src object number is not match.");
			return null;
		}

		Object targetO = null;
		try {
			@SuppressWarnings("rawtypes")
			Class clazz = Class.forName(bi.getName());
			try {
				targetO = clazz.newInstance();
			} catch (InstantiationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return null;
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return null;
			}
		} catch (ClassNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			return null;
		}

		// get the field value
		for (Object o : oArray) {

			for (SourceBean sb : bi.getBeanArray()) {

				String srcBean = sb.getSrcBeanName();

				try {

					// matach the object type
					if (o.getClass().equals(Class.forName(srcBean))) {

						BeanWrapper bwSrcO = new BeanWrapperImpl(o);
						BeanWrapper bwTargetO = new BeanWrapperImpl(targetO);

						for (BeanField bf : sb.getFields()) {

							Object valueO = bwSrcO.getPropertyValue(bf
									.getSrcFieldName());
							bwTargetO.setPropertyValue(bf.getTargFieldName(),
									valueO);

						}

					} else {

						// if not the class , then continue
						continue;
					}
				} catch (ClassNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					System.out.println("===> Can't find Class :" + srcBean);
					return null;
				}

			}

		}

		return targetO;
	}

}
